//
//  LoginVC.m
//  SH_JSK
//
//  Created by duwl on 1/27/15.
//  Copyright (c) 2015 asiainfo. All rights reserved.
//

#import "LoginViewController.h"
#import "CommonMacro.h"
#import "UIImage+LXX.h"
#import "RegisterViewController.h"
#import "myTabBarViewController.h"
#import "AppDelegate.h"
#import "FindCodeViewController.h"
//#import "InterfaceViewController.h"
//#import "ViewController.h"
#import "MBProgressHUD.h"
#import "JKAlert.h"



@interface LoginViewController ()<UITextFieldDelegate>

{
    UIView *myBgView;
}

@property (nonatomic,strong) UITextField  *userNameField;
@property (nonatomic,strong) UITextField  *userCodeField;
@property (nonatomic,strong) NSDictionary *SendDic;
@property (nonatomic,copy)   NSString     *user;
@property (nonatomic,copy)   NSString     *code;

-(void)finished:(FinishedLogin)finished;

@end

@implementation LoginViewController



-(void)viewWillAppear:(BOOL)animated{
    
//    
//    [_userNameField resignFirstResponder];
//    [_userCodeField resignFirstResponder];
//    if([_userNameField.text length]==0){
//        [self showSimpleAlertView:@"请输入账户"];
//    }else if([_userCodeField.text length]==0){
//        [self showSimpleAlertView:@"请输入密码"];
//    }else{
//        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        NSDictionary *param = @{@"userName": _userNameField.text,@"password":_userCodeField.text};
//        [UserDAL getUser:param success:^(UserModel *user) {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            NSString *userId = _userNameField.text;
//            NSString *userCode = _userCodeField.text;
//            
//            
//            NSString *ID = user.userId;
//            [[NSUserDefaults standardUserDefaults] setObject:ID forKey:@"ID"];
//            ////NSLog(@"%@呃呃呃呃呃呃呃呃呃",ID);
//            
//            
//            [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
//            [[NSUserDefaults standardUserDefaults] setObject:userCode forKey:@"userCode"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//            myTabBarViewController * myTableView = [[myTabBarViewController alloc]init];
//            [self  presentViewController:myTableView animated:YES completion:nil];
//#warning: 把登陆后的用户存入单例中   参照博客 http://www.skyfox.org/ios-login-info-save.html
//            [AppDelegate APP].user = user;
//            if (_finished) {
//                [self dismissViewControllerAnimated:YES completion:^{
//                    _finished(user);
//                }];
//            }
//        } failed:^(NSError *error) {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            [JKAlert showMessage:@"提示" message:error];
//            //            myTabBarViewController * myTableView = [[myTabBarViewController alloc]init];
//            //            [self  presentViewController:myTableView animated:YES completion:nil];
//            
//            ////NSLog(@"%@",error);
//            //            myTabBarViewController * myTableView = [[myTabBarViewController alloc]init];
//            //            [self  presentViewController:myTableView animated:YES completion:nil];
//        }];
//        
//        //在此处发送请求
//    }
//    

    
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
//    [self.navigationController.navigationBar setTranslucent:NO];//设置navigationbar的半透明
//    self.title = @"登陆";//设置navigationbar上显示的标题
//    [self.navigationController.navigationBar setBarTintColor:[GetFileModel colorWithHexString:@"#ff763a" alpha:1]];
    self.navigationItem.rightBarButtonItem.title = @"注册";
    [self.navigationController.navigationBar setBarTintColor:[GetFileModel colorWithHexString:@"#ef5858" alpha:1]];
    self.view.backgroundColor = [UIColor whiteColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [self.view addGestureRecognizer:tap];
    
    //设置导航栏头文字
    self.navigationItem.title = @"登录";
    //设置导航栏背景颜色
    [self.navigationController.navigationBar setBarTintColor:[GetFileModel colorWithHexString:@"#ef5858" alpha:1]];
    //设置导航栏字体颜色
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
//    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]
//                                 initWithTitle:@"注册"
//                                 style:UIBarButtonItemStylePlain
//                                 target:self
//                                 action:@selector(tap:)];
//    [rightBtn setTintColor:[UIColor whiteColor]];
//    self.navigationItem.rightBarButtonItem = rightBtn;

    
    
    
    
    
    
    
    
}

-(void)loadView
{
    self.view =[[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self layout];
}


- (void)tap:(UITapGestureRecognizer *)recognizer
{
    
    if (IS_IPHONE_4_OR_LESS) {
        
        myBgView.frame =CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT);
        
        
    }
    else
    {
        
        myBgView.frame = CGRectMake(0, 20-NavbarHight, SCREEN_WIDTH, SCREEN_HEIGHT+NavbarHight+20);
        
        
    }

    [_userNameField resignFirstResponder];
    [_userCodeField resignFirstResponder];
    
    //NSLog(@"我失败了");

    
}

-(void)layout
{
    if (IS_IPHONE_4_OR_LESS) {
        UIScrollView *bgView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT)];
        bgView.contentSize = CGSizeMake(SCREEN_WIDTH, 568);
        bgView.backgroundColor = [UIColor whiteColor];
        bgView.showsVerticalScrollIndicator = FALSE;
        bgView.showsHorizontalScrollIndicator = FALSE;

        [self.view addSubview:bgView];
        myBgView = bgView;
    }
    else
    {
        
//        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT+NavbarHight+20)];
//        bgView.backgroundColor = [UIColor whiteColor];
//        [self.view addSubview:bgView];
//        myBgView = bgView;
        
        UIScrollView *bgView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 20-NavbarHight, SCREEN_WIDTH, SCREEN_HEIGHT+NavbarHight+20)];
        bgView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT+NavbarHight+20);
        bgView.backgroundColor = [UIColor whiteColor];
        bgView.showsVerticalScrollIndicator = FALSE;
        bgView.showsHorizontalScrollIndicator = FALSE;

        [self.view addSubview:bgView];
        myBgView = bgView;

        
    }
    
    UIImageView *iconImg = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-50, 40, 100, 100)];
    iconImg.image = [UIImage imageNamed:@"sign_login"];
    [myBgView addSubview:iconImg];
    
    
    UIView *LoginView = [[UIView alloc]initWithFrame:CGRectMake(20, 150+NavbarHight, SCREEN_WIDTH-40, 100)];
    LoginView.layer.borderColor = UIColorWithRGBA(232, 234, 237, 1).CGColor;
    LoginView.layer.borderWidth = 1;
    LoginView.layer.cornerRadius = 8;
    [myBgView addSubview:LoginView];
    
    UIView *middleLine = [[UIView alloc]initWithFrame:CGRectMake(0, 50, SCREEN_WIDTH-40, 1)];
    [LoginView addSubview:middleLine];
    middleLine.backgroundColor = UIColorWithRGBA(232, 234, 237, 1);
    
    
    UIImageView *UserImg = [[UIImageView alloc]initWithFrame:CGRectMake(15,20, 12, 20)];
    UserImg.image = [UIImage imageNamed:@"_0002s_0005_手机"];
    [LoginView addSubview:UserImg];
    
    UIImageView *CodeImg = [[UIImageView alloc]initWithFrame:CGRectMake(15,65,12,20)];
    CodeImg.image = [UIImage imageNamed:@"_0002s_0008_密码"];
    [LoginView addSubview:CodeImg];
    
    
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *myString1 = [userDefaultes stringForKey:@"userId"];
//    NSString *myString2 = [userDefaultes stringForKey:@"userCode"];
    NSString *myString2 = @"";

    _userNameField = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, SCREEN_WIDTH-40, 35)];
    _userNameField.text = myString1;
    _userNameField.delegate = self;
    _userNameField.returnKeyType = UIReturnKeyNext;
    _userNameField.placeholder = @"请输入用户名";
    _userNameField.keyboardType = UIKeyboardTypeNumberPad;
    
    
    _userCodeField = [[UITextField alloc]initWithFrame:CGRectMake(40, 60, SCREEN_WIDTH-40, 35)];
    _userCodeField.text = myString2;
    _userCodeField.placeholder = @"输入密码,长度6-16位";
    _userCodeField.delegate = self;
    _userCodeField.returnKeyType = UIReturnKeyDone;
    _userCodeField.secureTextEntry = YES;
    [LoginView addSubview:_userNameField];
    [LoginView addSubview:_userCodeField];
    
//    UIButton *loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(20, 280, SCREEN_WIDTH-40, 50)];
//    loginBtn.backgroundColor = [GetFileModel colorWithHexString:@"#ef5858" alpha:1];
//    loginBtn.layer.cornerRadius = 5;
//    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
//    [loginBtn addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
//    [myBgView addSubview:loginBtn];
    UIImageView * headImage = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-326/4, NavbarHight-20-5+NavbarHight/2, 326/2, 254/2)];
    headImage.image = [UIImage imageNamed:@"icon.png"];
//    headImage.backgroundColor = [UIColor redColor];
    [myBgView addSubview:headImage];
    
    
    
    UIButton * btnClick = [UIButton buttonWithType:UIButtonTypeCustom];
    btnClick.frame = CGRectMake(20, 280+NavbarHight, SCREEN_WIDTH-40,50);
    [btnClick setBackgroundImage:[UIImage imageNamed:@"red@2x"] forState:UIControlStateNormal];
    [btnClick setBackgroundImage:[UIImage imageNamed:@"redScl@2x"] forState:UIControlStateHighlighted];
    [btnClick setTitle:@"登录" forState:UIControlStateNormal];
    [btnClick setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btnClick.titleLabel.textAlignment = NSTextAlignmentCenter;
    [btnClick addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    btnClick.userInteractionEnabled = YES;
    [myBgView addSubview:btnClick];
    
    
    
    UIButton *FogetBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-110, 350+NavbarHight, 100, 30)];
    [FogetBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    FogetBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [FogetBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [FogetBtn setBackgroundColor:[UIColor clearColor]];
    [FogetBtn addTarget:self action:@selector(forget) forControlEvents:UIControlEventTouchUpInside];
    [myBgView addSubview:FogetBtn];
    
    UIButton *RegistBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-70, 7, 50, 30)];
    [RegistBtn setTitle:@"注册" forState:UIControlStateNormal];
    [RegistBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [RegistBtn addTarget:self action:@selector(regist) forControlEvents:UIControlEventTouchUpInside];
//    RegistBtn.backgroundColor = UIColorWithRGBA(219, 99, 101, 1);
    [self.navigationController.navigationBar addSubview:RegistBtn];
    
    UIButton *passWordSwitch = [[UIButton alloc] initWithFrame:CGRectMake(LoginView.bounds.size.width-60,50,50,50)];
    [passWordSwitch setImage:[UIImage imageNamed:@"_0002s_0000_眼-副本"] forState:UIControlStateNormal];
    [passWordSwitch setImage:[UIImage imageNamed:@"_0002s_0001_眼"] forState:UIControlStateSelected];
    [passWordSwitch addTarget:self action:@selector(changeSecureTextEntry:) forControlEvents:UIControlEventTouchUpInside];
    [LoginView addSubview:passWordSwitch];
}


-(void)login:(id)sender
{
    [_userNameField resignFirstResponder];
    [_userCodeField resignFirstResponder];
    if([_userNameField.text length]==0){
        
                [self showSimpleAlertView:@"请输入账户"];
    }else if([_userCodeField.text length]==0){
        [self showSimpleAlertView:@"请输入密码"];
    }else
    if(![self isMobileNumber:_userNameField.text]) {
        [JKAlert showMessage:@"提示" message:@"手机号码不合法"];
    }else{
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSDictionary *param = @{@"userName": _userNameField.text,@"password":_userCodeField.text};
        [UserDAL getUser:param success:^(UserModel *user) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            NSString *userId = _userNameField.text;
            NSString *userCode = _userCodeField.text;
            
            
            NSString *ID = user.userId;
            [[NSUserDefaults standardUserDefaults] setObject:ID forKey:@"ID"];
            ////NSLog(@"%@呃呃呃呃呃呃呃呃呃",ID);


            
            
            [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults] setObject:userCode forKey:@"userCode"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            
            
            
            myTabBarViewController * myTableView = [[myTabBarViewController alloc]init];
            myTableView.showPg = @"是我";
            [self  presentViewController:myTableView animated:YES completion:nil];
        
            
#warning: 把登陆后的用户存入单例中   参照博客 http://www.skyfox.org/ios-login-info-save.html
            [AppDelegate APP].user = user;
            if (_finished) {
                [self dismissViewControllerAnimated:YES completion:^{
                    _finished(user);
                }];
            }
        } failed:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [JKAlert showMessage:@"提示" message:error];
//            //NSLog(@"%@",error);
//            myTabBarViewController * myTableView = [[myTabBarViewController alloc]init];
//            [self  presentViewController:myTableView animated:YES completion:nil];
            
            ////NSLog(@"%@",error);
            //            myTabBarViewController * myTableView = [[myTabBarViewController alloc]init];
            //            [self  presentViewController:myTableView animated:YES completion:nil];
        }];
        
        //在此处发送请求
        
        
    }
    
    

//    myTabBarViewController * myTableView = [[myTabBarViewController alloc]init];
//    [self  presentViewController:myTableView animated:YES completion:nil];
//
    
    
}

- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    if (mobileNum.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178
     * 联通号段: 130,131,132,155,156,185,186,145,176
     * 电信号段: 133,153,180,181,189,177
     */
    
    
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9])\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178
     */
    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176
     */
    NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177
     */
    NSString *CT = @"^1(33|53|77|8[019])\\d{8}$";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    //开始编辑时触发，文本字段将成为first responder
    //NSLog(@"我开始了");
    
    if (IS_IPHONE_4_OR_LESS) {
        
        myBgView.frame =CGRectMake(0, 20-75, SCREEN_WIDTH, SCREEN_HEIGHT);
        
        
           }
    else
    {
        
        myBgView.frame = CGRectMake(0, 20-NavbarHight-75, SCREEN_WIDTH, SCREEN_HEIGHT+NavbarHight+20);
        
        
    }

    
//    UIScrollView *bgView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT)];
//    UIScrollView *bgView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 20-NavbarHight, SCREEN_WIDTH, SCREEN_HEIGHT+NavbarHight+20)];
    
    
}
-(void)finished:(FinishedLogin)finished{
    _finished = finished;
}



- (void)changeSecureTextEntry:(UIButton *)mySwitch
{
    mySwitch.selected = !mySwitch.selected;
    _userCodeField.secureTextEntry = !mySwitch.selected;
}

-(void)forget
{
    FindCodeViewController *regist = [[FindCodeViewController alloc]init];
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:regist];
    [self  presentViewController:nav animated:YES completion:nil];
}

-(void)regist
{
    RegisterViewController *regist = [[RegisterViewController alloc]init];
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:regist];
    [self  presentViewController:nav animated:YES completion:nil];
}

-(void)showSimpleAlertView:(NSString*)message
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示信息"
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}


- (void)requestDidFinished:(NSDictionary*)info
{
    [[NSUserDefaults standardUserDefaults] setObject:_userNameField.text forKey:@"userName"];
    [[NSUserDefaults standardUserDefaults] setObject:_userCodeField.text forKey:@"userCode"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)requestFailed:(NSDictionary*)info
{
    [self showSimpleAlertView:@"登录失败"];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    
    if (IS_IPHONE_4_OR_LESS) {
        
        myBgView.frame =CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT);
        
        
    }
    else
    {
        
        myBgView.frame = CGRectMake(0, 20-NavbarHight, SCREEN_WIDTH, SCREEN_HEIGHT+NavbarHight+20);
        
        
    }

    //NSLog(@"我失败了");
    if (textField == _userNameField) {
        [_userCodeField becomeFirstResponder];
    } else {
        [textField resignFirstResponder];
    }
    return NO;
}
@end
